package com.zut.service.impl;


import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.extension.api.R;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.zut.pojo.MyPage;
import com.zut.utils.JwtTokenUtil;
import com.zut.mapper.ManagerMapper;
import com.zut.pojo.Manager;
import com.zut.pojo.Result;
import com.zut.service.ManagerService;
import com.zut.utils.DateUtil;
import com.zut.utils.MailUtil;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.core.userdetails.UserDetailsService;
import org.springframework.security.crypto.password.PasswordEncoder;
import org.springframework.stereotype.Service;
import org.springframework.util.StringUtils;

import javax.mail.MessagingException;
import javax.servlet.http.HttpServletRequest;
import java.text.ParseException;
import java.util.HashMap;
import java.util.Map;


/**
 * @author: Mr.Liu
 * @create: 2021-11-04 12:43
 */
@Service
public class ManagerServiceImpl implements ManagerService {
    @Autowired
    ManagerMapper managerMapper;

    @Autowired
    JwtTokenUtil jwtTokenUtil;

    @Autowired
    UserDetailsService userDetailsService;

    @Autowired
    PasswordEncoder passwordEncoder;

    @Autowired
    MailUtil mailUtil;

    @Autowired
    DateUtil dateUtil;

    @Value("${jwt.tokenHead}")
    private String tokenHead;

    private static final Logger logger = LoggerFactory.getLogger(ManagerServiceImpl.class);

    @Override
    public Result login(String username, String password, String code, HttpServletRequest request) {
        //拿到验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        //先判断验证码是否正确
        if (!StringUtils.hasText(code) || !captcha.equalsIgnoreCase(code)) {
            return Result.error("验证码填写错误");
        }
        UserDetails userDetails = userDetailsService.loadUserByUsername(username);

//        if (null==userDetails||!passwordEncoder.matches(password,userDetails.getPassword())) {
//           return Result.error("用户名和密码不能为空");
//        }
        //调用MyBatisPlus接口里的查询方法
        QueryWrapper<Manager> wrapper = new QueryWrapper<>();
        wrapper.eq("username", username);
        Manager manager = managerMapper.selectOne(wrapper);
        if (!password.equals(manager.getPassword())) {
            return Result.error("用户名或密码不正确");
        }
        //更新用户登录次数
        Integer num = manager.getNum();

        int i = managerMapper.updateById(new Manager(manager.getId(), null, null, null, null, ++num, null, null, null));
        if (i == 1) {
            logger.info("更新用户登录次数成功");
        } else {
            logger.warn("更新用户登录信息失败");
        }

        //更新security登录用户对象
        UsernamePasswordAuthenticationToken authenticationToken = new
                UsernamePasswordAuthenticationToken(userDetails,
                null, userDetails.getAuthorities());
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);


        //根据用户名生成token
        String token = jwtTokenUtil.generateToken(userDetails);
        //存在map集合中一起返回前端
        Map<String, String> tokenMap = new HashMap<>();
        tokenMap.put("token", token);
        tokenMap.put("tokenHead", tokenHead);

        if (manager.getAuths().lastIndexOf("admin") >= 0) {
            tokenMap.put("roles", "admin");
        } else {
            tokenMap.put("roles", "user");
        }
        return Result.success("登录成功", tokenMap);
    }


    /**
     * 根据用户名获取用户
     *
     * @param username
     * @return
     */
    @Override
    public Manager getManagerByUserName(String username) {
        return managerMapper
                .selectOne(new QueryWrapper<Manager>().eq("username", username));
    }

    @Override
    public Result register(String username, String password, String code, String email, HttpServletRequest request){
        //拿到验证码
        String captcha = (String) request.getSession().getAttribute("captcha");
        //先判断验证码是否正确
        if (!StringUtils.hasText(code) || !captcha.equalsIgnoreCase(code)) {
            return Result.error("验证码填写错误");
        }
        Manager manager = new Manager(null, username, password, email, "user", 0, dateUtil.getDate(), dateUtil.getDate(), 0);
        managerMapper.insert(manager);
        try {
            mailUtil.sendMail(email,username,password);
        } catch (MessagingException e) {
            e.printStackTrace();
        }
        logger.info("邮件正在发送中......");
        return Result.success("注册成功，请重新登录");
    }

    @Override
    public Result getAllManager(Integer current) {
        if ("".equals(current)||current==null){
            return Result.error("当前页不能为空");
        }
        Page<Manager> selectPage = managerMapper.selectPage(new Page<Manager>(current, 7), new QueryWrapper<Manager>().eq("auths", "user"));


        return Result.success("分页查询成功", new MyPage<Manager>(current, selectPage.getTotal(), selectPage.getPages(), selectPage.getRecords()));
    }

    @Override
    public Result updateUserRoles(Integer id) {
        int i = managerMapper.updateById(new Manager(id, null, null, null, "admin", null, null, null, null));
        if (i==1){
            return Result.success("权限升级成功");
        }else {
            return Result.error("权限升级失败");
        }
    }


}
